#ifdef RUNTIME
#define _GNU_SOURCE 
#include<stdio.h>
#include<string.h>
#include"sm4.h"
#include<string.h>
#include <stdlib.h>
#include<dlfcn.h>
unsigned char key[16]={"1234567890123456"};

FILE* fopen(const char * path,const char * mode)
{
      FILE *(*lib_fopen)(const char * path,const char * mode);
      char * error;
      lib_fopen = dlsym(RTLD_NEXT, "fopen");
      if ((error = dlerror()) != NULL) {
        fputs(error, stderr);
        exit(1);
      }
      FILE * result = lib_fopen(path,mode);
      printf("this is my open\n");
      return result;
}

int fseek( FILE *stream, long offset, int origin )
{
      int (*lib_fseek)( FILE *stream, long offset, int origin );
      char * error;
      lib_fseek = dlsym(RTLD_NEXT, "fseek");
      if ((error = dlerror()) != NULL) {
        fputs(error, stderr);
        exit(1);
      }
      int result = lib_fseek(stream,offset,origin);
      printf("this is my seek\n");
      return result;
}
size_t fwrite(const void*buffer,size_t size,size_t count,FILE*stream)
{
sm4_context ctx;
int length;
if(size%16!=0)
   length=(size/16+1)*16;
else
   length=size;
printf("%d",length);
unsigned char *output=(unsigned char*)alloca(length);
unsigned char *input=(unsigned char*)alloca(length);
memcpy(input,buffer,length);  
sm4_setkey_enc(&ctx, key); //设置秘钥
sm4_crypt_ecb(&ctx, 0, length, input, output); //加密
sm4_crypt_ecb(&ctx, 0, length, output, input); //加密
      int (*lib_fwrite)(const void*buffer,size_t size,size_t count,FILE*stream);
      char * error;
      lib_fwrite = dlsym(RTLD_NEXT, "fwrite");
      if ((error = dlerror()) != NULL) {
        fputs(error, stderr);
        exit(1);
      }
      printf("this is my write\n");
      return lib_fwrite(output,length,count,stream);
}
size_t fread(void *ptr,size_t size, size_t nitems, FILE *stream)
{
      int length;
      if(size%16!=0)
         length=(size/16+1)*16;
      else
         length=size;
      printf("this is my read\n");
      unsigned char *input=(unsigned char*)alloca(length);
      unsigned char *output=(unsigned char*)malloc(length);
      int (*lib_fread)(void *ptr, int size, int nitems, FILE *stream);
      char * error;
      lib_fread = dlsym(RTLD_NEXT, "fread");
      if ((error = dlerror()) != NULL) {
        fputs(error, stderr);
        exit(1);
      }
      printf("this is my write\n");
      size_t result=lib_fread(input,length,nitems,stream);
      sm4_context ctx;
      sm4_setkey_dec(&ctx, key); //设置秘钥,与加密过程唯一不同的地方
      sm4_crypt_ecb(&ctx, 0, length, input, output); //解密
      memcpy(ptr,output,length);  
      return result;
}
#endif

